<template>
  <!-- 如果有子菜单 -->
  <el-sub-menu v-if="item.children" :index="resolvePath(item.path)">
    <template #title>
      <i>
        <svg-icon :size="iconSize" class="my-icon" :iconClass="item.meta.icon" />
      </i>
      <span>{{ item.meta.title }}</span>
    </template>

    <!-- 遍历子菜单并递归渲染 -->
    <sidebar-item
        v-for="child in item.children"
        :key="child.path"
        :item="child"
        :parent-path="resolvePath(item.path)"
    />
  </el-sub-menu>

  <!-- 否则是普通菜单项 -->
  <el-menu-item v-else :index="resolvePath(item.path)" @click="handleClick">
    <i>
      <svg-icon :size="iconSize" class="my-icon" :iconClass="item.meta.icon" />
    </i>
    <span>{{ item.meta.title }}</span>
  </el-menu-item>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { ref } from 'vue';

const props = defineProps({
  item: {
    type: Object,
    required: true,
  },
  parentPath: {
    type: String,
    default: '', // 接收父级的路径
  },
});

const router = useRouter();
const iconSize = ref('18px');

// 拼接路径
const resolvePath = (path) => {
  // 如果是根路径或者已经是绝对路径，直接返回
  if (path.startsWith('/')) {
    return path;
  }
  // 拼接父级路径和子路径
  return props.parentPath ? `${props.parentPath}/${path}` : `/${path}`;
};

// 点击事件处理
const handleClick = () => {
  const fullPath = resolvePath(props.item.path);
  console.log("Navigating to:", fullPath); // 输出完整路径
  router.push(fullPath).catch(err => {
    // 忽略重复导航的错误
    if (err.name !== 'NavigationDuplicated') {
      console.error(err);
    }
  });
};
</script>

<style scoped>
.my-icon {
  margin: 0 12px 0 0;
}
.el-menu-item span,
.el-sub-menu__title span {
  user-select: none;
  font-weight: 100;
  font-size: 13px;
}
.el-sub-menu__title i,
.el-menu-item i {
  display: flex;
  align-items: center;
}
</style>
